import { ApiBaseRefreshToken } from "../../api/api.base";
import { ApiLogin } from "../../api/api.login";
import { ApiPalmDivince } from "../../api/api.plam";
import { NodeApi, StorageTokenKey, UploadImageMaxSize } from "../../utils/config";
import { ApiLoginReqInterface, ApiLoginResInterface } from "../../interface/api.login.interface";
import { ResInterface } from "../../interface/request.interface";
import { AsyncHideLoading, AsyncShowLoading, AsyncShowToast, CheckSession, ChooseImage, GetAppId, GetLocal, GetMD5, Login, OpenModal, OpenSetting, RedirectTo, SetLocal, ToPage } from "../../utils/common";
import { IsEmpty, RecursionObject } from "../../utils/util";
import { ApiPalmReqInterface } from "../../interface/api.palm.interface";

// pages/palm.upload/palm.upload.ts
Page({

  // 页面的初始数据
  data: {
    // 相机
    cameraShow: false, // 相机是否显示
    // 上传图片信息
    imagePath: '', // 地址
    imageId: 0, // 上传成功之后返回的id
    imageMd5: '', // 图片md5
    imageWidth: '', // 图片宽度
    imageHeight: '', // 图片高度
    imageSize: '', // 图片大小
  },

  // 生命周期函数--监听页面加载
  async onLoad() {
    try {
      // 用户信息
      const _CheckSession: boolean = await CheckSession();
      console.log('_CheckSession', _CheckSession)
      if (_CheckSession) {
        const _GetLocal = await GetLocal(StorageTokenKey);
        if (!_GetLocal['token']) {
          await this.login();
        }
      } else {
        await this.login();
      }
      // 刷新token
      // await this.refreshToken();
    } catch (error) {
      await AsyncShowToast(error);
    }
  },

  // 生命周期函数--监听页面初次渲染完成
  onReady() {

  },

  // 生命周期函数--监听页面显示
  onShow() {

  },

  // 生命周期函数--监听页面隐藏
  onHide() {

  },

  // 生命周期函数--监听页面卸载
  onUnload() {

  },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh() {

  },

  // 页面上拉触底事件的处理函数
  onReachBottom() {

  },

  // 用户点击右上角分享
  onShareAppMessage() {

  },
  // 登录
  async login(): Promise<boolean> {
    try {
      const _Login: string = await Login();
      console.log('客户端获取的', _Login);
      const _GetAppId: string = await GetAppId();
      console.log('AppId', _GetAppId)
      const _data: ApiLoginReqInterface = {
        app_id: _GetAppId,
        code: _Login,
      };
      console.log('登录参数', _data)
      const _ApiLogin: ResInterface = await ApiLogin({
        data: _data
      });
      console.log('登录返回值', _ApiLogin)
      const { code, data, message } = _ApiLogin;
      if (code === 200) {
        const _data: ApiLoginResInterface = {
          token: data['token'] || '',
        };
        await SetLocal(StorageTokenKey, _data);
        return true;
      } else {
        throw message || '登录接口请求失败';
      }
    } catch (error) {
      console.log('error', error)
      throw error;
    }
  },
  // 选择图片
  async onChooseImage() {
    try {
      const _chooseImage = await ChooseImage({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album'],
        sizeType: ['compressed']
      });
      console.log('_chooseImage', _chooseImage)
      const { errMsg, tempFiles } = _chooseImage;
      console.log('选择图片1', errMsg, tempFiles, _chooseImage)
      let _status: boolean = true; // 流程正常执行
      if (errMsg === 'chooseMedia:fail auth deny') {
        _status = false;
        console.log('选择照片没权限')
        const _OpenModal = await OpenModal(
          '权限申请',
          '在设置权限中开启摄像头权限，允许使用相机功能',
        );
        if (_OpenModal) {
          await OpenSetting();
        }
        await RedirectTo('upload');
        return;
      } else if (errMsg === "chooseMedia:ok") {
        _status = true;
      } else {
        _status = false;
      }
      if (!_status) return;
      // 判定是否存在选择的数据
      const _size: number = tempFiles[0]['size']
      if (!_size) {
        throw '图片大小为空';
      }
      const _tempFilePath: string = tempFiles[0]['tempFilePath']
      if (!_tempFilePath) {
        throw '图片临时路径为空';
      }
      // 验证图片大小
      if (_size > UploadImageMaxSize) {
        throw '图片大于2M';
      } else {
        this.setData({
          imageSize: String(tempFiles[0]['size']),
        });
      }
      await AsyncShowLoading('上传中...');
      // 生成md5
      const _getMD5: string = await GetMD5(_tempFilePath);
      console.log('_getMD5', _getMD5)
      this.setData({
        imageMd5: _getMD5,
      })
      // 上传
      const _uploadFile = await this.uploadFile(_tempFilePath);
      console.log('上传1', _uploadFile);
      const {
        code,
        data,
        message,
      } = _uploadFile
      if (code === 200) {
        this.setData({
          imageId: data['id'],
          imagePath: data['full_url'],
        });
        await AsyncHideLoading();
      } else {
        await AsyncHideLoading();
        await OpenModal('提示', message);
      }
    } catch (error) {
      console.log('选择图片-错误', error)
      await AsyncHideLoading();
      await AsyncShowToast(error);
    }
  },

  // 拍照上传
  async onTakePhoto() {
    console.log(456)
    try {
      const _ChooseImage = await ChooseImage({
        count: 1,
        mediaType: ['image'],
        sourceType: ['camera'],
        sizeType: ['compressed']
      }); // 拍照
      const { errMsg, tempFiles } = _ChooseImage;
      console.log('_ChooseImage', _ChooseImage)
      let _status: boolean = true; // 流程正常执行
      if (errMsg === 'chooseImage:fail auth deny') {
        _status = false;
        console.log('相机没授权')
        const _OpenModal = await OpenModal(
          '权限申请',
          '在设置权限中开启摄像头权限，允许使用相机功能',
        );
        if (_OpenModal) {
          await OpenSetting();
        }
        await RedirectTo('upload');
        return;
      } else if (errMsg === "chooseImage:ok") {
        _status = true;
      } else {
        _status = false;
      }
      if (!_status) return;
      // 验证图片大小
      if (tempFiles[0]['size'] > UploadImageMaxSize) {
        throw '图片大于2M';
      } else {
        this.setData({
          imageSize: String(tempFiles[0]['size']),
        });
      }
      await AsyncShowLoading('上传中...');
      // 生成md5
      const _getMD5 = await GetMD5(tempFiles[0]['tempFilePath']);
      console.log('拍照上传2', _getMD5)
      if (_getMD5) {
        this.setData({
          imageMd5: _getMD5,
        })
      }
      // 上传
      const _uploadFile = await this.uploadFile(tempFiles[0]['tempFilePath']); // 上传
      console.log('拍照上传3', _uploadFile)
      const {
        code,
        data,
        message,
      } = _uploadFile
      if (code === 200) {
        this.setData({
          imageId: parseInt(data?.id),
          imagePath: data?.full_url,
        });
        await AsyncHideLoading();
      } else {
        await AsyncHideLoading();
        await OpenModal(
          '提示',
          message,
        );
      }
    } catch (error) {
      console.log('拍照上传-错误', error)
      await AsyncHideLoading();
      await AsyncShowToast(error);
    }
  },

  // 上传
  async uploadFile(path: string): Promise<any> {
    if (!path) {
      throw '未选择图片';
    };
    const _GetAppId: string = await GetAppId();
    const _formData: Object = {
      md5: this.data.imageMd5,
      width: this.data.imageWidth,
      height: this.data.imageHeight,
      size: this.data.imageSize,
      app_id: _GetAppId,
      safety_verify: 1, // 需要安全检测
    }
    RecursionObject(_formData, IsEmpty);
    const _GetLocal = await GetLocal(StorageTokenKey);
    const _token: string = _GetLocal['token'];
    if (!_token) {
      await this.login();
    }
    const _header: any = {
      authorization: _token,
    };
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${NodeApi}/v1/api/upload/image`,
        filePath: path,
        name: "file",
        header: _header,
        formData: _formData,
        success: (res) => {
          console.log('上传3', res)
          if (res?.errMsg === "uploadFile:ok") {
            try {
              let _data = {};
              _data = JSON.parse(res?.data);
              resolve(_data)
            } catch (error) {
              reject('解析返回值失败');
            }
          } else {
            reject('上传失败');
          }
        },
        fail: (err) => {
          console.log('上传错误', err);
          reject('上传错误');
        },
      });
    });
  },

  // 手动调用刷新token
  async refreshToken() {
    try {
      const _GetAppId: string = await GetAppId();
      const _data: Object = {
        app_id: _GetAppId,
      };
      const _ApiBaseRefreshToken = await ApiBaseRefreshToken({ data: _data });
      console.log('手动刷新token', _ApiBaseRefreshToken)
    } catch (error) {
      throw error;
    }
  },

  /**
   * 分析
   * @description 测试图片 http://static_source.yihcm.com/douyin_mini_face/test.jpeg
   */
  async onDivince() {
    try {
      if (!this.data.imagePath || !this.data.imageId) {
        console.log('imagePath/imageId')
        throw ('请选择图片或拍照');
      }
      await AsyncShowLoading('分析中...');
      const _data: ApiPalmReqInterface = {
        image_url: this.data.imagePath,
        image_id: this.data.imageId,
      };
      console.log('ApiFaceDivince1', _data)
      const _ApiPalmDivince = await ApiPalmDivince({
        data: _data,
      });
      console.log('_ApiPalmDivince2', _ApiPalmDivince)
      const { code, message } = _ApiPalmDivince;
      await AsyncHideLoading();
      if (code === 200) {
        await AsyncShowToast('分析成功正在跳转');
        await ToPage('/pages/palm.detail/palm.detail');
      } else {
        throw message || '分析失败';
      }
    } catch (error) {
      console.log('onDivince', error)
      await AsyncHideLoading();
      await AsyncShowToast(error);
    }
  },
})